package com.ruix.app.widget.clip;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * User: Ray
 * Date: 15/10/10
 * ReadMe: 图片裁剪工具类
 */
public class ImageClipUtil {

    public static Bitmap getBitmapFromUri(Activity activity, Uri originalUri, boolean isFromCamera) throws Exception {
        Bitmap bitmap = null;
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        bmpFactoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
        BitmapFactory.decodeStream(
                activity.getContentResolver().openInputStream(originalUri),
                null,
                bmpFactoryOptions);

        int mHorizontalPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, activity.getResources().getDisplayMetrics());
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int targetWidth = display.getWidth() - 2 * mHorizontalPadding;

        int outWidth = bmpFactoryOptions.outWidth;
        int outHeight = bmpFactoryOptions.outHeight;


        float scaleWidth = 0.f, scaleHeight = 0.f;
        if (outWidth > targetWidth || outHeight > targetWidth) {
            // 缩放
            scaleWidth = ((float) outWidth) / targetWidth;
            scaleHeight = ((float) outHeight) / targetWidth;
        }

        bmpFactoryOptions.inJustDecodeBounds = false;

        float scale = Math.max(scaleWidth, scaleHeight);
        bmpFactoryOptions.inSampleSize = (int) (scale * 1.5);// Ray备注：为适配高清图片需要将图片压缩率，增加1.5倍

        bitmap = BitmapFactory.decodeStream(
                activity.getContentResolver().openInputStream(originalUri),
                null,
                bmpFactoryOptions);
        if (isFromCamera) {// 来自相机拍摄
            bitmap = autoRotateImage(bitmap, getCameraFileName(activity));
        }
        return bitmap;
    }


    // 如果是相机拍摄，则进行相应的调整方向
    private static Bitmap autoRotateImage(Bitmap bitmap, String filePath) {
        int digree = 0;
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            exif = null;
            return bitmap;
        }
        if (exif != null) {
            // 读取图片中相机方向信息
            int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
            // 计算旋转角度
            switch (ori) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    digree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    digree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    digree = 270;
                    break;
                default:
                    digree = 0;
                    break;
            }
        }
        if (digree != 0) {
            // 旋转图片
            Matrix m = new Matrix();
            m.postRotate(digree);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
        }
        return bitmap;
    }


    public static String getCameraFileName(Context context) {
        String fileDirectroy = "";
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())
                && Environment.getExternalStorageDirectory().exists()) {
            fileDirectroy = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + SD_TMP_DIRECTORY;
        } else {
            fileDirectroy = context.getFilesDir().getAbsolutePath()
                    + SD_TMP_DIRECTORY;
        }

        File file = new File(fileDirectroy);
        if (!file.exists()) {
            file.mkdirs();
        }
        return Environment.getExternalStorageDirectory().getPath()
                + "/" + SD_TMP_DIRECTORY + "temp.jpg";
    }
    public static final String SD_TMP_DIRECTORY = "/hiwifi/" + "tmp/";


    public static String getExternalTemPath(){
        return Environment.getExternalStorageDirectory().getPath()+SD_TMP_DIRECTORY;
    }


    /** 保存图片到w */
    public static String saveBitmapToExternalTem(String name,Bitmap bm) {
        File f = new File(getExternalTemPath(), name);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            return f.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
